<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{path:'/',name:'Index'}">首页</el-breadcrumb-item>
      <el-breadcrumb-item>{{ curStatus }}</el-breadcrumb-item>
    </el-breadcrumb>
    <div class="blog-box">
      <el-form ref="blogForm" :model="blogForm" :rules="rules" label-position="right">
        <el-row>
          <el-col :span="20" :offset="2">
            <el-form-item prop="title">
              <el-row>
                <el-col :span="2">
                  <el-dropdown @command="getFlag">
                    <el-button type="success" plain>
                      {{ blogForm.flag }}<i class="el-icon-arrow-down el-icon--right"></i>
                    </el-button>
                    <el-dropdown-menu slot="dropdown">
                      <el-dropdown-item command="原创">原创</el-dropdown-item>
                      <el-dropdown-item command="转载">转载</el-dropdown-item>
                      <el-dropdown-item command="翻译">翻译</el-dropdown-item>
                    </el-dropdown-menu>
                  </el-dropdown>
                </el-col>
                <el-col :span="22">
                  <el-input v-model.trim="blogForm.title" placeholder="请输入博客标题"></el-input>
                </el-col>
              </el-row>
            </el-form-item>
            <el-form-item>
              <el-row>
                <el-col :span="24">
                  <mavon-editor style="z-index: 80;" ref="md" class="blog-edit" v-model="blogForm.content"
                                :ishljs="false"
                                @imgAdd="imgAdd"
                                @imgDel="imgDel"></mavon-editor>
                </el-col>
              </el-row>
            </el-form-item>
            <el-row style="margin-top: 20px;" :gutter="20">
              <el-col :span="17">
                <el-row>
                  <el-col :span="22">
                    <el-form-item label="博客描述" prop="description">
                      <el-input type="textarea" :row="2" placeholder="请输入博客描述..."
                                v-model.trim="blogForm.description"></el-input>
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row>
                  <el-col :span="12">
                    <el-form-item label="分类" prop="categoryId">
                      <el-select v-model="blogForm.categoryId" placeholder="请选择">
                        <el-option
                          v-for="item in categoryList"
                          :key="item.id"
                          :value="item.id"
                          :label="item.categoryName"></el-option>
                      </el-select>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="标签" prop="tagNames">
                      <el-select
                        v-model="blogForm.tagNames"
                        multiple
                        filterable
                        allow-create
                        default-first-option
                        placeholder="请选择文章标签">
                        <el-option
                          v-for="item in tagList"
                          :key="item.id"
                          :label="item.tagName"
                          :value="item.tagName">
                        </el-option>
                      </el-select>
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row>
                  <el-col :span="10">
                    <el-form-item label="公开类型" prop="publicType">
                      <el-select
                        v-model="blogForm.publicType"
                        placeholder="请选择文章公开类型">
                        <el-option
                          v-for="item in publicList"
                          :key="item.publicValue"
                          :label="item.publicName"
                          :value="item.publicValue">
                        </el-option>
                      </el-select>
                    </el-form-item>
                  </el-col>
                  <el-col :span="6" v-if="false">
                    <el-form-item label="开启赞赏">
                      <el-switch
                        v-model="blogForm.admire"
                        active-color="#13ce66"
                        inactive-color="#ff4949"
                        :active-value="1"
                        :inactive-value="0">
                      </el-switch>
                    </el-form-item>
                  </el-col>
                  <el-col :span="6">
                    <el-form-item label="开启评论">
                      <el-switch
                        v-model="blogForm.commentEnable"
                        active-color="#13ce66"
                        inactive-color="#ff4949"
                        :active-value="1"
                        :inactive-value="0">
                      </el-switch>
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row>
                  <el-col :span="6">
                    <el-form-item label="置顶">
                      <el-switch
                        v-model="blogForm.top"
                        active-color="#13ce66"
                        inactive-color="#ff4949"
                        :active-value="1"
                        :inactive-value="0">
                      </el-switch>
                    </el-form-item>
                  </el-col>
                  <el-col :span="6">
                    <el-form-item label="转载声明">
                      <el-switch
                        v-model="blogForm.shareStatement"
                        active-color="#13ce66"
                        inactive-color="#ff4949"
                        :active-value="1"
                        :inactive-value="0">
                      </el-switch>
                    </el-form-item>
                  </el-col>
                  <el-col :span="10">
                    <el-row type="flex" justify="flex-end">
                      <el-col :span="12">
                        <el-button type="primary" size="medium" @click="reset('blogForm')">
                          <i class="el-icon-refresh btn-icon"></i>重置
                        </el-button>
                      </el-col>
                      <el-col :span="12">
                        <el-button type="success" size="medium" @click="save('blogForm')">
                          <i class="iconfont icon-baocun btn-icon"></i>保存
                        </el-button>
                      </el-col>
                    </el-row>
                  </el-col>
                </el-row>
              </el-col>
              <el-col :span="7">
                <el-upload
                  class="upload-demo"
                  :file-list="fileList"
                  drag
                  :action="this.$api.IMG_UPLOAD_URL"
                  list-type="picture"
                  :limit="1"
                  :on-exceed="onExceed"
                  :before-remove="beforeRemove"
                  :on-success="onSuccess"
                  :accept="accept"
                  :headers="header"
                  :on-error="onError"
                  :on-preview="onPreview">
                  <i class="el-icon-upload"></i>
                  <div class="el-upload__text">上传文章首图，将文件拖到此处，或<em>点击上传</em></div>
                  <div class="el-upload__tip" slot="tip">只能上传{{ accept }}文件，且不超过2MB</div>
                </el-upload>
              </el-col>
            </el-row>
          </el-col>
        </el-row>
      </el-form>
    </div>
    <div style="margin-top: 20px;"></div>
    <el-dialog :visible.sync="dialogVisible" width="35%" :modal="false">
      <img width="100%" :src="this.blogForm.picture" alt="">
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: "BlogSave",
  data() {
    return {
      curStatus: "添加博客",
      dialogVisible: false,
      accept: '.jpg,.jpeg,.png,.gif,.tiff',
      fileList: [],
      header: {
        Authorization: this.$store.getters.getToken
      },
      blogForm: {
        id: null,
        flag: "原创",
        title: "",
        content: "",
        picture: "",
        categoryId: "",
        tagNames: [],
        description: "",
        publicType: "",
        admire: 1,
        commentEnable: 1,
        top: 1,
        shareStatement: 1,
        userId: this.$store.getters.getUserInfo.id
      },
      tagList: [],
      categoryList: [],
      publicList: [
        {
          publicName: "草稿",
          publicValue: 0
        },
        {
          publicName: "公开",
          publicValue: 1
        },
        {
          publicName: "仅自己可见",
          publicValue: 2
        }
      ],
      rules: {
        title: [
          {required: true, message: "请输入文章标题", trigger: 'blur'},
          {max: 100, message: "最多输入100个字符", trigger: 'blur'}
        ],
        description: [
          {required: true, message: "请输入文章描述", trigger: 'blur'},
          {max: 250, message: "最多输入250个字符", trigger: 'blur'}
        ],
        categoryId: [
          {required: true, message: "请选择文章分类", trigger: 'change'}
        ],
        tagNames: [
          {required: true, message: "请选择文章标签", trigger: 'change'}
        ],
        publicType: [
          {required: true, message: "请选择文章公开类型", trigger: 'change'}
        ]
      }
    }
  },
  created() {
    this.getTagList();
    this.getCategoryList();
    if (this.$route.params.id != "sj") {
      this.getBlogById(this.$route.params.id);
      this.curStatus = "编辑博客";
    } else {
      this.curStatus = "添加博客";
      this.$nextTick(() => {
        this.$refs['blogForm'].resetFields();
      })
    }
  },
  methods: {
    imgAdd(pos, $file) {
      let formData = new FormData();
      formData.append('file', $file);
      this.$post(this.$api.IMG_UPLOAD_URL, formData).then(res => {
        console.log(res)
        if (res.data.code == 200) {
          this.$refs.md.$imglst2Url([[pos, res.data.data.url]])
        }
      })
    },
    imgDel(pos) {
      this.$del(this.$api.IMG_DELETE_URL, {
        fileName: pos[0].substr(pos[0].indexOf('sjblog'))
      }).then(res => {
        if (res.data.code == 200) {
          this.$notify.success("图片删除成功");
        }
      });
    },
    getBlogById(id) {
      this.$get(this.$api.BLOG_DETAIL_URL, {
        blogId: id,
        userId: this.$store.getters.getUserInfo.id
      }).then(res => {
        if (res.data.code == 200) {
          this.blogForm = res.data.data;
          this.blogForm.tagNames = [];
          res.data.data.tagList.forEach(item => {
            this.blogForm.tagNames.push(item.tagName);
          });
          if (res.data.data.picture) {
            this.fileList.push({
              name: "博客首图",
              url: res.data.data.picture
            })
          }
        }
      })
    },
    getCategoryList() {
      this.$get(this.$api.CATEGORY_LIST_URL + `/${this.$store.getters.getUserInfo.id}/1/100`, {}).then(res => {
        if (res.data.code == 200) {
          this.categoryList = res.data.data.records;
        }
      })
    },
    getTagList() {
      this.$get(this.$api.TAG_LIST_URL + `/${this.$store.getters.getUserInfo.id}/1/100`, {}).then(res => {
        if (res.data.code == 200) {
          this.tagList = res.data.data.records;
        }
      })
    },
    reset(formName) {
      this.$confirm("确定重置所有已编辑内容吗？", "提示", {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$refs[formName].resetFields();
      }).catch(() => {
        this.$notify.info("已取消重置");
      })
    },
    save(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if (this.blogForm.content.trim() == "") {
            this.$notify.error("请输入文章内容");
            return false;
          }
          const loading = this.$loading({
            lock: true,
            text: 'Loading',
            spinner: 'el-icon-loading',
            background: 'rgba(0, 0, 0, 0.7)',
            customClass: 'loading-text',
            target: document.querySelector(".auth-panel")
          });
          let data = JSON.parse(JSON.stringify(this.blogForm));
          data.tagNames = data.tagNames.join(',');
          data.userId = this.$store.getters.getUserInfo.id;
          data.createTime = null;
          data.updateTime = null;
          this.$put(this.$api.SAVE_BLOG_URL, data).then(res => {
            if (res.data.code == 200) {
              this.$notify({
                title: '成功',
                message: res.data.message,
                type: "success"
              })
              this.$router.push({
                path: "/admin/blog",
                name: "BlogList"
              })
            }
            loading.close();
          })
        }
      });
    },
    getFlag(val) {
      this.blogForm.flag = val;
    },
    onExceed(files, fileList) {
      this.$notify.error("只允许上传一张图片哦")
    },
    onSuccess(response, file, fileList) {
      if (response.code == 200) {
        this.$notify.success("上传成功");
        this.blogForm.picture = response.data.url;
      }
    },
    onPreview(file) {
      this.dialogVisible = true;
    },
    onError(err, file, fileList) {
      this.$notify.error(JSON.parse(err.message).message);
    },
    beforeRemove(file, fileList) {
      return this.$confirm("您确定删除该照片吗？", "提示", {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$del(this.$api.IMG_DELETE_URL, {
          fileName: this.blogForm.picture.substr(this.blogForm.picture.indexOf('sjblog'))
        }).then(res => {
          if (res.data.code == 200) {
            this.$notify.success(res.data.message);
            this.blogForm.picture = "";
            this.fileList = [];
            if (this.blogForm.id) {
              this.$post(this.$api.UPDATE_BLOG_URL, {
                id: this.blogForm.id,
                userId: this.$store.getters.getUserInfo.id,
                picture: ""
              }).then(res => {
                console.log(res);
              })
            }
          }
        })
      }).catch(() => {
        this.$notify.info("已取消删除");
        this.reject(false);
      });
    },
  },
  watch: {
    $route(newUrl, oldUrl) {
      if (newUrl.params.id == "sj") {
        this.curStatus = "添加博客"
        this.blogForm.content = "";
        this.fileList = [];
        this.$refs['blogForm'].resetFields();
      }
    }
  }
}
</script>

<style scoped>
.blog-box {
  margin-top: 30px;
}

.upload-demo {
  min-width: 50% !important;
}

.blog-edit {
  margin-top: 20px;
  min-height: 50vh;
}

.btn-icon {
  font-size: 16px;
  margin-right: 5px;
}
</style>
